<template>
  <view class="viewport">
    <view class="header" :style="{ paddingTop: safeAreaInsets!.top + 'px' }">
      <view class="left icon-left" @tap="Onleft()"></view>
      <uni-title type="h1" align="center" title="月账单" class="text"></uni-title>
    </view>
    <view class="search">
      <view class="searchDate">
        <uni-datetime-picker
          class="searchDate"
          border="false"
          clear-icon="false"
          v-model="range"
          type="daterange"
          start="2024-1-1"
          end="2034-12-30"
          rangeSeparator="至"
          @change="changeDate"
        />
      </view>
      <view class="searchbox">
        <picker
          @change="pickerAccountTypeChange"
          mode="selector"
          :range="accountTypeNames"
          range-key="AccountTypeName"
        >
          <text class="account">{{ curAccountTypeName.AccountTypeName }}</text></picker
        >
      </view>
      <button class="button btn" @click="exportExcelData">导出</button>
    </view>
    <!-- 具体明细 -->
    <scroll-view enable-back-to-top scroll-y class="scroll">
      <uni-table ref="table" border stripe emptyText="暂无更多数据">
        <uni-tr>
          <uni-th :width="thWidth" align="center">年月</uni-th>
          <uni-th :width="thWidth" align="center">月收入</uni-th>
          <uni-th :width="thWidth" align="center">月支出</uni-th>
          <uni-th :width="thWidth" align="center">月余额</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in data" :key="index">
          <uni-td>{{ item.DealMonth > 0 ? item.DealYear + '-' + item.DealMonth : '合计' }}</uni-td>
          <uni-td>
            <view align="center">{{ item.InTotal }}</view>
          </uni-td>
          <uni-td align="center">{{ item.OutTotal }}</uni-td>
          <uni-td align="center">{{ item.Total }}</uni-td>
        </uni-tr>
      </uni-table>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ExportToExcelAPI, GetMonthCountType } from '@/services/count'
import { GetAccountTypeNameAPI, GetUserAccountAPI, GetUserSettingAPI } from '@/services/detail'
import { NoteIndex } from '@/services/notelog'
import { useMemberStore } from '@/stores'
import type { GetMonthCountResponse } from '@/types/count'
import type { AccountTypeNameResponse, UserAccount } from '@/types/detail'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const accountTypeNames = ref<AccountTypeNameResponse[]>()
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取会员信息
const memberStore = useMemberStore()
const data = ref<GetMonthCountResponse[]>()
const loading = ref<boolean>(false)
const thWidth = ref<number>()
const curAccountTypeName = ref<AccountTypeNameResponse>({
  AccountTypeName: 'ALL',
})
const range = ref(['2024-03-8', '2024-4-20'])
//加载初始化
onLoad(async () => {
  const date = new Date()
  range.value[0] = `${date.getFullYear()}-1-1`
  range.value[1] = getCurDate()
  thWidth.value = uni.getSystemInfoSync().windowWidth / 4
  //初始化账户类别
  await InitAccountTypeName()
  reFresh()
})
//获取当前时间
const getCurDate = () => {
  const date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  return `${year}-${month}-${day}`
}
//选择一行
const tapOne = async (year: number, month: number) => {
  if (memberStore.profile) {
    const userTitle = '月总结' + year + '-' + month
    const res = await NoteIndex({
      Auth: memberStore.profile.Token,
      UserName: '',
      ID: 0,
      UserTitle: userTitle,
      NoteType: '',
      UserGroup: memberStore.profile.UserGroup,
    })
    if (res.result.length > 0) {
      uni.navigateTo({
        url: '/pages/NoteAcount/NoteLog?UserTitle=' + userTitle + '&ID=' + res.result[0].ID,
      })
    } else {
      uni.navigateTo({
        url: '/pages/NoteAcount/NoteLog?UserTitle=' + userTitle + '&ID=19',
      })
    }
  }
}
//刷新事件
const reFresh = async () => {
  if (memberStore.profile) {
    const res = await GetMonthCountType({
      AccountTypeName: curAccountTypeName.value.AccountTypeName,
      Auth: memberStore.profile.Token,
      BeginTime: range.value[0],
      EndTime: range.value[1],
      UserName: memberStore.profile.UserName,
      UserGroup: memberStore.profile.UserGroup,
    })
    data.value = res.result
    loading.value = true
    uni.showToast({ icon: 'success', title: '刷新成功' })
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
}
//初始化账户类型列表
const InitAccountTypeName = async () => {
  if (memberStore.profile) {
    const res = await GetAccountTypeNameAPI({
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push({
      AccountTypeName: 'ALL',
    })
    res.result.push({
      AccountTypeName: '剔除股票收益',
    })
    accountTypeNames.value = res.result
  }
}
//选择账户类型
const pickerAccountTypeChange = (e: any) => {
  const index = e.detail.value as number
  curAccountTypeName.value = accountTypeNames.value![index]
  reFresh()
}
//选择日期
const changeDate = (e: any) => {
  reFresh()
}
//返回
const Onleft = () => {
  uni.switchTab({ url: '/pages/my/my' })
}
//导出
const exportExcelData = async () => {
  if (memberStore.profile) {
    const res = await ExportToExcelAPI({
      AccountTypeName: curAccountTypeName.value.AccountTypeName,
      Auth: memberStore.profile.Token,
      BeginTime: range.value[0],
      EndTime: range.value[1],
      UserName: memberStore.profile.UserName,
      UserGroup: memberStore.profile.UserGroup,
    })
    uni.showToast({ icon: 'success', title: '导出成功' })
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
}
</script>

<style lang="scss">
@import './styles/monthCount.scss';
</style>
